package com.huanwei.login_regist;


import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.RemoteException;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.Toast;

import com.amap.api.maps.AMap;
import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapsInitializer;
import com.amap.api.maps.SupportMapFragment;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.Polyline;
import com.amap.api.maps.model.PolylineOptions;
import com.huanwei.cc.CheliangGuiJi;
import com.huanwei.cc.R;

import com.huanwei.cc.utils.JSONUtils;
import com.huanwei.http.API;
import com.huanwei.http.Okhttp;
import com.kaopiz.kprogresshud.KProgressHUD;

import java.util.ArrayList;
import java.util.List;

//import com.amap.api.maps2d.AMap;
//import com.amap.api.maps2d.AMapUtils;
//import com.amap.api.maps2d.CameraUpdateFactory;
//import com.amap.api.maps2d.MapsInitializer;
//import com.amap.api.maps2d.SupportMapFragment;
//import com.amap.api.maps2d.model.BitmapDescriptorFactory;
//import com.amap.api.maps2d.model.LatLng;
//import com.amap.api.maps2d.model.Marker;
//import com.amap.api.maps2d.model.MarkerOptions;
//import com.amap.api.maps2d.model.Polyline;
//import com.amap.api.maps2d.model.PolylineOptions;
//import com.huanwei.cc.R;

/**
 * 作业轨迹
 */
public class ZuoYeGuiJi_10_Activity extends FragmentActivity {
    private AMap mAMap;
    private Button mButton;
    private SeekBar mSeekBar;
    private Marker mCarMarker;
    private Polyline mPolyline;

    // 存放所有坐标的数组
    private final ArrayList<LatLng> mLatLngs = new ArrayList<>();
    private final ArrayList<LatLng> mTraceLatLngs = new ArrayList<>();

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                int pro = mSeekBar.getProgress();
                if (pro != mSeekBar.getMax()) {
                    mSeekBar.setProgress(pro + 1);

                    mHandler.sendEmptyMessageDelayed(1, 100);
                } else {
                    Button button = (Button) findViewById(R.id.btn_replay);
                    button.setText(" 回放 ");// 已执行到最后一个坐标 停止任务
                }
            }
        }
    };
    KProgressHUD dialog;

    String kaishixs;
    String name;
    String jieshuxs;

    public void showdialog() {
        dialog = KProgressHUD.create(ZuoYeGuiJi_10_Activity.this)
                .setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
                .setLabel("正在加载数据，请稍候")
                .setCancellable(true)
                .setAnimationSpeed(2)
                .setDimAmount(0.5f)
                .show();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_zuoyeguij);
        RelativeLayout img_back = (RelativeLayout) findViewById(R.id.img_back);
        name = getIntent().getStringExtra("name");

        img_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        initAmap();
        getguiji();
        float f = 0;
        for (int i = 0; i < mLatLngs.size() - 1; i++) {
            f += AMapUtils.calculateLineDistance(mLatLngs.get(i), mLatLngs.get(i + 1));
        }

    }

    //    String  VehId="282";
//    String   kaishixs="2018-08-01 00:00:00";
//    String  jieshuxs="2018-08-01 23:59:59";
    public void getguiji() {
        showdialog();
        API.VehicleTrack(name, new Okhttp.Objectcallback() {
            @Override
            public void onsuccess(String st) {
                Log.e("zzzz", "获取轨迹" + st);
                if (dialog != null) {
                    dialog.dismiss();
                }
                CheliangGuiJi cheliangGuiJi = JSONUtils.parseJSON(st, CheliangGuiJi.class);
                if (cheliangGuiJi.getCode() == 10001) {
                    List<CheliangGuiJi.DataBean> data = cheliangGuiJi.getData();
                    setUpMap(data);
                }

            }

            @Override
            public void onFalia(int code, String errst) {
                if (dialog != null) {
                    dialog.dismiss();
                }
                Log.e("zzzz", "获取轨迹错误" + errst);
                Toast.makeText(ZuoYeGuiJi_10_Activity.this, "获取轨迹网络错误", Toast.LENGTH_SHORT).show();
            }
        });

    }


//    FrameLayout map;

    /**
     * 初始化AMap对象
     */
    private void initAmap() {
//        map = (FrameLayout) findViewById(R.id.map);
        mButton = (Button) findViewById(R.id.btn_replay);
        mSeekBar = (SeekBar) findViewById(R.id.process_bar);
        mSeekBar.setSelected(false);

        mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onProgressChanged(SeekBar seekBar, int progress,
                                          boolean fromUser) {
                if (mPolyline == null) {
                    final PolylineOptions polylineOptions = new PolylineOptions(); //绘制轨迹线
                    polylineOptions.color(Color.GREEN).width(8.0f);
                    mPolyline = mAMap.addPolyline(polylineOptions);
                }

                mTraceLatLngs.clear();
                if (progress != 0) {
                    for (int i = 0; i < seekBar.getProgress(); i++) {
                        mTraceLatLngs.add(mLatLngs.get(i));
                    }
                    drawLine(mTraceLatLngs, progress);
                }

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

                mTraceLatLngs.clear();
                int current = seekBar.getProgress();
                if (current != 0) {
                    for (int i = 0; i < seekBar.getProgress(); i++) {
                        mTraceLatLngs.add(mLatLngs.get(i));
                    }
                    drawLine(mTraceLatLngs, current);
                }
            }
        });

//        if (mAMap == null) {
//            mAMap = ((SupportMapFragment) getSupportFragmentManager()
//                    .findFragmentById(R.id.map)).getMap();
//            if (mAMap != null) {
//                setUpMap();
//            }
//        }

        if (mAMap == null) {
            FragmentManager fm = getSupportFragmentManager();
            FragmentTransaction transaction = fm.beginTransaction();
            try {
//                setUpMap();
                MapsInitializer.initialize(this);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
            SupportMapFragment supportMapFragment = new SupportMapFragment();
            transaction.replace(R.id.navigation_map_fl, supportMapFragment);
            transaction.commit();
            mAMap = supportMapFragment.getMap();

        }

    }

    private void drawLine(ArrayList<LatLng> latLngs, int current) {
        LatLng replayGeoPoint = latLngs.get(current - 1);
        if (mCarMarker != null) {
            mCarMarker.destroy();
        }

        // 添加车辆位置
        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions
                .position(replayGeoPoint)
                .icon(BitmapDescriptorFactory
                        .fromBitmap(BitmapFactory.decodeResource(
                                getResources(), R.drawable.che)))
                .anchor(0.5f, 0.5f);
        mCarMarker = mAMap.addMarker(markerOptions);

        mAMap.animateCamera(CameraUpdateFactory.newLatLngZoom(replayGeoPoint, 15));

        if (latLngs.size() > 1) {
            mPolyline.setPoints(latLngs);
        }

        if (latLngs.size() == mLatLngs.size()) {
            mAMap
                    .addMarker(new MarkerOptions()
                            .position(latLngs.get(latLngs.size() - 1))
                            .icon(BitmapDescriptorFactory
                                    .fromBitmap(BitmapFactory
                                            .decodeResource(getResources(), R.drawable.nav_route_result_end_point))));
        }
    }

    private void setUpMap(List<CheliangGuiJi.DataBean> st) {

        for (int i = 0; i < st.size(); i++) {
            mLatLngs.add(new LatLng( Double.valueOf(st.get(i).getAchievement()),Double.valueOf(st.get(i).getName())));
        }


        // 设置进度条最大长度为数组长度
        mSeekBar.setMax(mLatLngs.size());
        mAMap.setMapType(AMap.MAP_TYPE_NORMAL);
        mAMap.moveCamera(CameraUpdateFactory.newLatLngZoom(mLatLngs.get(0), 15));
//        mAMap.moveCamera(CameraUpdateFactory.zoomTo(20));
        // 增加起点位置
        mAMap.addMarker(new MarkerOptions()
                .position(mLatLngs.get(0))
                .icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                        .decodeResource(
                                getResources(),
                                R.drawable.nav_route_result_start_point))));
    }

    public void btn_replay_click(View v) {
        // 根据按钮上的字判断当前是否在回放
        if (mButton.getText().toString().contains("回放")) {

            if (mLatLngs.size() > 0) {
                // 假如当前已经回放到最后一点 置0
                if (mSeekBar.getProgress() == mSeekBar.getMax()) {
                    mSeekBar.setProgress(0);
                }
                // 将按钮上的字设为"停止" 开始调用定时器回放
                mButton.setText(" 停止 ");
                mHandler.sendEmptyMessage(1);
            }
        } else {
            // 移除定时器的任务
            mHandler.removeMessages(1);
            mButton.setText(" 回放 ");
        }
    }

}

